package cipher.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import cipher.exception.IsNotCipherFileException;
import cipher.util.CipherConst;
import cipher.util.IFCrypt;

public class CipherFile  {
	private File physicalFile;
	private long encLen;
	private long orgLen;
	private IFCrypt cipher;
	private RandomAccessFile raf;
	
	public CipherFile(File physicalFile,IFCrypt cipher) {
		this.physicalFile =physicalFile;
		this.cipher = cipher;
		try {
			byte rbuf[] = new byte[CipherConst.enc_kBufferSize];
			encLen = physicalFile.length();
			raf = new RandomAccessFile(physicalFile, "rw");
			long lastblock = CipherConst.getEncodedLastBlockPosition(encLen);
			raf.seek(lastblock);
			int read = raf.read(rbuf, 0,rbuf.length);
			raf.close();
			byte[] v = cipher.decrypt(rbuf, 0, read);
			if(v!=null){
				orgLen =CipherConst.convert2decodedBlockPosition(lastblock) +v.length;
			}else{
				if(physicalFile.length()>0){
					throw new IsNotCipherFileException(physicalFile.getPath()+" is not a encrypted file or BAD KEY");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				raf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	
		
	}
	
	/**
	 * 
	 * @return 물리적 파일 
	 */
	
	public File getPhysicalFile(){
		return this.physicalFile;
	}
	/**
	 *  암호화 객체 
	 * @return 암호화 객체 
	 */
	public IFCrypt getCipher(){
		return this.cipher;
	}
	
	protected void setEncLength(long len){
		this.encLen = len;
	}
	/**
	 * 암호화된 파일 크기 
	 * @return 암호화된 파일크기  
	 */
	public long getEncLength(){
		return this.encLen;
	}
	
	protected void setLength(long len){
		this.orgLen = len;
	}
	/**
	 * 암호화 하기전 파일 크기 
	 * @return 복호화된 파일 크기 
	 */
	public long length(){
		return this.orgLen;
	}
	
	protected void close() throws IOException {

	}
	
}
